<template>
  <div class="notice-container">
    <!-- 顶部操作栏 -->
    <div class="top-bar">
      <div class="left-section">
        <h2 class="page-title">通知公告</h2>
        <div class="filter-tabs">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="全部" name="all"></el-tab-pane>
            <el-tab-pane label="新闻" name="NEWS"></el-tab-pane>
            <el-tab-pane label="通知" name="NOTICE"></el-tab-pane>
            <el-tab-pane label="活动" name="ACTIVITY"></el-tab-pane>
          </el-tabs>
        </div>
    </div>

      <div class="right-section">
        <!-- 搜索框 -->
        <div class="search-section">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索公告标题或内容"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
            style="width: 300px; margin-right: 15px;"
          >
            <template #prefix>
            <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>

        <!-- 管理员操作按钮 -->
        <div v-if="isAdmin" class="admin-actions">
          <el-button type="primary" @click="showPublishDialog = true">
            <el-icon><Plus /></el-icon>
            发布公告
          </el-button>
          <el-button type="warning" @click="openDraftDialog">
            <el-icon><Document /></el-icon>
            草稿箱
            <el-badge v-if="draftCount > 0" :value="draftCount" class="draft-badge" />
          </el-button>
          <el-button type="success" @click="openMyPublishDialog">
            <el-icon><User /></el-icon>
            我的发布
          </el-button>
    </div>

        <div v-else class="user-actions">
          <el-button v-if="!isStaff" type="info" @click="openMySignupDialog">
            <el-icon><User /></el-icon>
            我的报名
          </el-button>
        </div>
      </div>
    </div>

    <!-- 公告列表 -->
    <div class="notice-list" v-loading="loading">
      <div v-if="noticeList.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无公告" />
      </div>
      
      <el-row :gutter="20" v-else>
        <el-col :span="24">
          <el-card v-for="item in noticeList" :key="item.id" class="notice-item" :class="{ 'unread': !item.isRead }">
        <div class="notice-header">
          <div class="notice-title">
                <el-tag :type="getTagType(item.type)" size="small">{{ getTypeLabel(item.type) }}</el-tag>
                <span class="title-text">{{ item.title }}</span>
                <el-tag v-if="!item.isRead" type="danger" size="small">未读</el-tag>
                <el-tag v-if="item.type === 'ACTIVITY'" :type="getStatusType(item)" size="small">
                  {{ getStatusText(item) }}
            </el-tag>
          </div>
          <div class="notice-meta">
                <span class="publisher">发布者：{{ item.publisher }}</span>
                <span class="publish-time">{{ formatTime(item.publishTime) }}</span>
                <span v-if="item.type === 'ACTIVITY' && item.location" class="location">地点：{{ item.location }}</span>
          </div>
        </div>
        
        <div class="notice-footer">
              <div class="notice-actions">
                <el-button type="primary" size="small" @click="viewDetail(item)">
            查看详情
          </el-button>
                
                <!-- 活动报名按钮 -->
          <el-button 
                  v-if="item.type === 'ACTIVITY' && userRole !== 'ADMIN' && !isStaff"
                  type="success" 
                  size="small" 
                  @click="openSignupDialog(item)"
                  :disabled="!canUserSignup(item)"
                >
                  {{ getButtonText(item) }}
                </el-button>
                
                <!-- 管理员操作 -->
                <div v-if="isAdmin && item.publisher === currentUser" class="admin-item-actions">
                  <el-button type="danger" size="small" @click="deleteNotice(item)">
                    删除
                  </el-button>
                </div>
    </div>
              
              <!-- 活动状态信息 -->
              <div v-if="item.type === 'ACTIVITY'" class="activity-info">
                <span v-if="item.activityLimit" class="limit-info">
                  人数限制：{{ item.approvedCount || 0 }}/{{ item.activityLimit }}
                </span>
                <span v-if="item.signupDeadline" class="deadline-info">
                  报名截止：{{ formatTime(item.signupDeadline) }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

    <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </div>

    <!-- 发布公告对话框 -->
    <el-dialog
      v-model="showPublishDialog" 
      title="发布公告" 
      width="800px"
      :before-close="handleClosePublishDialog"
    >
      <el-form :model="publishForm" :rules="publishRules" ref="publishFormRef" label-width="100px">
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="publishForm.type" placeholder="请选择公告类型" style="width: 100%">
            <el-option label="新闻" value="NEWS"></el-option>
            <el-option label="通知" value="NOTICE"></el-option>
            <el-option label="活动" value="ACTIVITY"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="publishForm.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="publishForm.content" 
            type="textarea" 
            :rows="6"
            placeholder="请输入公告内容"
          ></el-input>
        </el-form-item>
        
        <!-- 地址字段只在活动类型时显示 -->
        <el-form-item v-if="publishForm.type === 'ACTIVITY'" label="地点" prop="location">
          <el-input v-model="publishForm.location" placeholder="请输入地点（可选）"></el-input>
        </el-form-item>
        
        <!-- 活动专属字段 -->
        <template v-if="publishForm.type === 'ACTIVITY'">
          <el-form-item label="人数上限" prop="activityLimit">
            <el-input-number v-model="publishForm.activityLimit" :min="1" :max="1000"></el-input-number>
          </el-form-item>
          
          <el-form-item label="报名截止时间" prop="signupDeadline">
            <el-date-picker
              v-model="publishForm.signupDeadline"
              type="datetime"
              placeholder="选择报名截止时间"
              style="width: 100%"
            />
          </el-form-item>
        </template>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="publishForm.remark" placeholder="请输入备注（可选）"></el-input>
        </el-form-item>
        
        <!-- 附件上传（仅新闻和通知类型） -->
        <el-form-item v-if="publishForm.type === 'NEWS' || publishForm.type === 'NOTICE'" label="附件" prop="attachments">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleAttachmentChange"
            :on-remove="handleAttachmentRemove"
            :file-list="attachmentList"
            multiple
          >
            <el-button type="primary">
              <el-icon><Plus /></el-icon>
              选择文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持doc、docx、pdf、xls、xlsx、ppt、pptx、txt等格式，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="图片" prop="images">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveAsDraft">保存草稿</el-button>
          <el-button type="primary" @click="publishNotice">发布公告</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 活动报名对话框 -->
    <el-dialog 
      v-model="showSignupDialog" 
      title="活动报名" 
      width="600px"
    >
      <el-form :model="signupForm" :rules="signupRules" ref="signupFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="signupForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="signupForm.studentId" placeholder="请输入学号"></el-input>
        </el-form-item>
        
        <el-form-item label="学院" prop="department">
          <el-input v-model="signupForm.department" placeholder="请输入学院"></el-input>
        </el-form-item>
        
        <el-form-item label="专业" prop="major">
          <el-input v-model="signupForm.major" placeholder="请输入专业"></el-input>
        </el-form-item>
        
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="signupForm.contact" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        
        <el-form-item label="相关经验" prop="experience">
          <el-input 
            v-model="signupForm.experience" 
            type="textarea" 
            :rows="4"
            placeholder="请描述您的相关经验（可选）"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSignupDialog = false">取消</el-button>
          <el-button type="primary" @click="submitSignup">提交报名</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 草稿箱对话框 -->
    <el-dialog
      v-model="showDraftDialog" 
      title="草稿箱" 
      width="800px"
      height="800px"
      :before-close="() => showDraftDialog = false"
    >
      <div class="draft-list" v-loading="loading">
        <div v-if="draftList.length === 0" class="empty-state">
          <el-empty description="暂无草稿" />
          </div>
        
        <el-card v-else v-for="draft in draftList" :key="draft.id" class="draft-item">
          <div class="draft-header">
            <el-tag :type="getTagType(draft.type)" size="small">{{ getTypeLabel(draft.type) }}</el-tag>
            <span class="draft-title">{{ draft.title }}</span>
            <span class="draft-time">{{ formatTime(draft.draftTime) }}</span>
        </div>
          
          <div class="draft-actions">
            <el-button type="primary" size="small" @click="editDraft(draft)">编辑</el-button>
            <el-button type="success" size="small" @click="publishDraft(draft)">发布</el-button>
            <el-button type="danger" size="small" @click="deleteDraft(draft)">删除</el-button>
        </div>
        </el-card>
      </div>
    </el-dialog>

    <!-- 我的报名对话框 -->
    <el-dialog
      v-model="showMySignupDialog" 
      title="我的报名" 
      width="800px"
      :before-close="() => showMySignupDialog = false"
    >
      <div class="my-signup-list" v-loading="loading">
        <div v-if="mySignupList.length === 0" class="empty-state">
          <el-empty description="暂无报名记录" />
        </div>
        
        <el-card v-else v-for="signup in mySignupList" :key="signup.signupId" class="signup-item">
          <div class="signup-header">
            <el-tag :type="getSignupStatusType(signup.signupStatus)" size="small">
              {{ getSignupStatusText(signup.signupStatus) }}
            </el-tag>
            <span class="signup-title">{{ signup.activityTitle }}</span>
            <span class="signup-time">{{ formatTime(signup.signupTime) }}</span>
          </div>
          
          <div class="signup-content">
            <p><strong>活动地点：</strong>{{ signup.activityLocation || '未设置' }}</p>
            <p><strong>报名时间：</strong>{{ formatTime(signup.signupTime) }}</p>
            <p><strong>活动状态：</strong>{{ getActivityStatusText(signup.activityStatus) }}</p>
            <p v-if="signup.activitySignupDeadline"><strong>报名截止：</strong>{{ formatTime(signup.activitySignupDeadline) }}</p>
          </div>
        </el-card>
      </div>
    </el-dialog>

    <!-- 我的发布对话框 -->
    <el-dialog
      v-model="showMyPublishDialog" 
      title="我的发布" 
      width="800px"
      :before-close="() => showMyPublishDialog = false"
    >
      <div class="my-publish-list" v-loading="loading">
        <div v-if="myPublishList.length === 0" class="empty-state">
          <el-empty description="暂无发布记录" />
        </div>
        
        <el-card v-else v-for="item in myPublishList" :key="item.id" class="publish-item">
          <div class="publish-header">
            <el-tag :type="getTagType(item.type)" size="small">{{ getTypeLabel(item.type) }}</el-tag>
            <span class="publish-title">{{ item.title }}</span>
            <span class="publish-time">{{ formatTime(item.publishTime) }}</span>
          </div>
          
          <div class="publish-actions">
            <el-button type="danger" size="small" @click="deletePublish(item)">删除</el-button>
            <el-button v-if="item.type === 'ACTIVITY'" type="info" size="small" @click="viewSignups(item)">查看报名</el-button>
          </div>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, onActivated, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Document, User, Search } from '@element-plus/icons-vue'
import { 
  apiGetAnnouncementList, 
  apiPublishAnnouncement, 
  apiDeleteAnnouncement,
  apiSaveDraft,
  apiGetDraftList,
  apiPublishDraft,
  apiDeleteDraft,
  getMyAnnouncements,
  uploadAttachment,
  uploadImage
} from '@/api/announcement'
import { submitActivitySignup, getUserSignupDetails } from '@/api/activitySignup'
import { useRouter } from 'vue-router'
import { 
  getActivityStatusType, 
  getActivityStatusText, 
  getSignupButtonText,
  getSignupStatusType,
  getSignupStatusText,
  canSignup
} from '@/utils/activityStatus'

export default {
  name: 'NoticePage',
  components: {
    Plus,
    Document,
    User,
    Search
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    
    // 响应式数据
    const activeTab = ref('all')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const noticeList = ref([])
    const draftList = ref([])
    const mySignups = ref([])
    const mySignupList = ref([])
    const myAnnouncements = ref([])
    const myPublishList = ref([])
    const searchKeyword = ref('')
    const loading = ref(false)
    const loadingMyAnnouncements = ref(false)
    const draftCount = ref(0)
    
    // 图片列表
    const imageList = ref([])
    
    // 附件列表
    const attachmentList = ref([])
    
    // 对话框状态
    const showPublishDialog = ref(false)
    const showSignupDialog = ref(false)
    const showDraftDialog = ref(false)
    const showMySignups = ref(false)
    const showMySignupDialog = ref(false)
    const showMyAnnouncements = ref(false)
    const showMyPublishDialog = ref(false)
    
    // 表单数据
    const publishForm = reactive({
      type: '',
      title: '',
      content: '',
      location: '',
      remark: '',
      images: '',
      activityLimit: null,
      signupDeadline: null,
      signupUrl: '',
      attachments: []
    })
    
    const signupForm = reactive({
      activityId: null,
      name: '',
      studentId: '',
      department: '',
      major: '',
      contact: '',
      experience: ''
    })
    
    // 从store获取用户信息
    const currentUser = computed(() => store.state.user.userInfo.username || 'admin')
    const userRole = computed(() => store.getters['user/role'] || 'STUDENT')
    const isStaff = computed(() => userRole.value === 'STAFF')
    const userId = computed(() => {
      const userInfo = store.state.user.userInfo
      if (userInfo && userInfo.id) {
        return userInfo.id
      }
      return null
    })
    
    // 调试信息
    console.log('Store user info:', {
      id: store.state.user.userInfo.id,
      username: store.state.user.userInfo.username,
      role: store.state.user.userInfo.role
    })
    console.log('Computed userId:', userId.value)
    
    // 计算属性
    const isAdmin = computed(() => userRole.value === 'ADMIN')
    
    // 监听公告类型变化，清空地址信息
    watch(() => publishForm.type, (newType) => {
      if (newType !== 'ACTIVITY') {
        publishForm.location = ''
      }
    })
    
    // 表单验证规则
    const publishRules = {
      type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
      content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
    }
    
    const signupRules = {
      name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
      studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
      major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
      contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }]
    }
    
    // 方法
    const loadNoticeList = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          userId: userId.value
        }
        if (activeTab.value !== 'all') {
          params.type = activeTab.value
        }
        if (searchKeyword.value) {
          params.keyword = searchKeyword.value
        }
        const response = await apiGetAnnouncementList(params)
        if (response.code === 200) {
          // 归一化数据结构，保证item.id可用
          if (Array.isArray(response.data) && response.data.length > 0 && response.data[0].announcement) {
            noticeList.value = response.data.map(item => ({
              ...item.announcement,
              isRead: item.isRead,
              readTime: item.readTime,
              approvedCount: item.approvedCount // 添加已通过的人数
            }))
          } else {
            noticeList.value = response.data
          }
          total.value = response.total || response.data.length
        }
      } catch (error) {
        ElMessage.error('加载公告列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const loadDraftList = async () => {
      try {
        const response = await apiGetDraftList({
          publisher: currentUser.value
        })
        if (response.code === 200) {
          draftList.value = response.data
        }
      } catch (error) {
        ElMessage.error('加载草稿列表失败')
      }
    }
    
    const loadMySignups = async () => {
      try {
        // 使用新的基于用户ID的API
        const response = await getUserSignupDetails()
        if (response.code === 200) {
          mySignupList.value = response.data
        } else {
          ElMessage.error(response.message || '加载我的报名失败')
        }
      } catch (error) {
        console.error('加载我的报名失败:', error)
        ElMessage.error('加载我的报名失败')
      }
    }
    
    const loadMyAnnouncements = async () => {
      loadingMyAnnouncements.value = true
      try {
        const response = await getMyAnnouncements({ publisher: currentUser.value })
        if (response.code === 200) {
          myPublishList.value = response.data
        }
      } catch (error) {
        ElMessage.error('加载我的发布失败')
      } finally {
        loadingMyAnnouncements.value = false
      }
    }

    const getTagType = (type) => {
      const types = {
        'NEWS': 'primary',
        'NOTICE': 'warning',
        'ACTIVITY': 'success'
      }
      return types[type] || 'info'
    }

    const getTypeLabel = (type) => {
      const labels = {
        'NEWS': '新闻',
        'NOTICE': '通知',
        'ACTIVITY': '活动'
      }
      return labels[type] || type
    }
    
    const formatTime = (time) => {
      if (!time) return ''
      return new Date(time).toLocaleString()
    }
    
    const getStatusType = (item) => {
      return getActivityStatusType(item.status, item.signupDeadline)
    }
    
    const getStatusText = (item) => {
      return getActivityStatusText(item.status, item.signupDeadline)
    }
    
    const getButtonText = (item) => {
      return getSignupButtonText(item, mySignupList.value)
    }
    
    const canUserSignup = (item) => {
      return canSignup(item, mySignupList.value)
    }
    
    const viewDetail = (item) => {
      // 跳转到详情页面
      router.push({
        name: 'NoticeDetail',
        params: { id: item.id }
      })
    }
    
    const openSignupDialog = (item) => {
      signupForm.activityId = item.id
      showSignupDialog.value = true
    }
    
    const submitSignup = async () => {
      try {
        // 使用正确的活动报名API
        const response = await submitActivitySignup(signupForm)
        if (response.code === 200) {
          ElMessage.success('报名成功')
          showSignupDialog.value = false
          // 重置表单
          Object.assign(signupForm, {
            activityId: null,
            name: '',
            studentId: '',
            department: '',
            major: '',
            contact: '',
            experience: ''
          })
        } else {
          ElMessage.error(response.message || '报名失败')
        }
      } catch (error) {
        ElMessage.error('报名失败')
      }
    }
    
    const publishNotice = async () => {
      try {
        // 添加发布者信息
        const announcementData = {
          ...publishForm,
          publisher: currentUser.value,
          images: imageList.value.map(item => item.url).join(','),
          attachments: attachmentList.value.map(item => ({
            name: item.name,
            url: item.url,
            size: item.size,
            type: item.type
          }))
        }
        
        const response = await apiPublishAnnouncement(announcementData)
        if (response.code === 200) {
          ElMessage.success('发布成功')
          showPublishDialog.value = false
          loadNoticeList()
          // 重置表单
          Object.assign(publishForm, {
            type: '',
            title: '',
            content: '',
            location: '',
            remark: '',
            images: '',
            activityLimit: null,
            signupDeadline: null,
            signupUrl: '',
            attachments: []
          })
          // 清空附件列表和图片列表
          attachmentList.value = []
          imageList.value = []
        } else {
          ElMessage.error(response.message || '发布失败')
        }
      } catch (error) {
        ElMessage.error('发布失败')
      }
    }
    
    const saveAsDraft = async () => {
      try {
        const draftData = {
          ...publishForm,
          publisher: currentUser.value,
          images: imageList.value.map(item => item.url).join(','),
          attachments: attachmentList.value.map(item => ({
            name: item.name,
            url: item.url,
            size: item.size,
            type: item.type
          }))
        }
        
        const response = await apiSaveDraft(draftData)
        if (response.code === 200) {
          ElMessage.success('草稿保存成功')
          showPublishDialog.value = false
          loadDraftList()
          // 重置表单
          Object.assign(publishForm, {
            type: '',
            title: '',
            content: '',
            location: '',
            remark: '',
            images: '',
            activityLimit: null,
            signupDeadline: null,
            signupUrl: '',
            attachments: []
          })
          // 清空附件列表和图片列表
          attachmentList.value = []
          imageList.value = []
        } else {
          ElMessage.error(response.message || '保存失败')
        }
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
    
    const handleClosePublishDialog = () => {
      showPublishDialog.value = false
      // 重置表单
      Object.assign(publishForm, {
        type: '',
        title: '',
        content: '',
        location: '',
        remark: '',
        images: '',
        activityLimit: null,
        signupDeadline: null,
        signupUrl: '',
        attachments: []
      })
      // 清空附件列表和图片列表
      attachmentList.value = []
      imageList.value = []
    }
    
    const deleteNotice = async (item) => {
      try {
        await ElMessageBox.confirm('确定要删除这条公告吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await apiDeleteAnnouncement(item.id, {
          publisher: currentUser.value
        })
        
        if (response.code === 200) {
          ElMessage.success('删除成功')
          loadNoticeList()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const editDraft = (draft) => {
      // 跳转到编辑页面
      router.push({
        name: 'NoticeEdit',
        params: { id: draft.id }
      })
    }
    
    const publishDraft = async (draft) => {
      try {
        const response = await apiPublishDraft(draft.id, {
          publisher: currentUser.value
        })
        
        if (response.code === 200) {
          ElMessage.success('草稿发布成功')
          loadDraftList()
          loadNoticeList()
        } else {
          ElMessage.error(response.message || '发布失败')
        }
      } catch (error) {
        ElMessage.error('发布失败')
      }
    }
    
    const deleteDraft = async (draft) => {
      try {
        await ElMessageBox.confirm('确定要删除这个草稿吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await apiDeleteDraft(draft.id, {
          publisher: currentUser.value
        })
        
        if (response.code === 200) {
          ElMessage.success('删除成功')
          loadDraftList()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handleImageChange = async (file) => {
      try {
        // 调用后端API上传图片
        const response = await uploadImage(file.raw)
        if (response.code === 200) {
          // 上传成功，添加到图片列表
          imageList.value.push({
            name: response.data.name,
            url: response.data.url,
            size: response.data.size,
            type: response.data.type
          })
          ElMessage.success('图片上传成功')
        } else {
          ElMessage.error(response.message || '图片上传失败')
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        ElMessage.error('图片上传失败')
      }
    }
    
    const handleImageRemove = (file) => {
      // 图片移除处理逻辑
      console.log('图片删除:', file)
      const index = imageList.value.findIndex(item => item.name === file.name)
      if (index > -1) {
        imageList.value.splice(index, 1)
      }
    }
    
    const handleAttachmentChange = async (file) => {
      try {
        // 调用后端API上传文件
        const response = await uploadAttachment(file.raw)
        if (response.code === 200) {
          // 上传成功，添加到附件列表
          attachmentList.value.push({
            name: response.data.name,
            url: response.data.url,
            size: response.data.size,
            type: response.data.type
          })
          ElMessage.success('附件上传成功')
        } else {
          ElMessage.error(response.message || '附件上传失败')
        }
      } catch (error) {
        console.error('附件上传失败:', error)
        ElMessage.error('附件上传失败')
      }
    }
    
    const handleAttachmentRemove = (file) => {
      // 附件移除处理逻辑
      console.log('附件删除:', file)
      const index = attachmentList.value.findIndex(item => item.name === file.name)
      if (index > -1) {
        attachmentList.value.splice(index, 1)
      }
    }
    
    const handleTabClick = (tab) => {
      // 更新activeTab为当前点击的标签页
      activeTab.value = tab.props.name
      currentPage.value = 1
      loadNoticeList()
    }

    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      loadNoticeList()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadNoticeList()
    }
    
    const handleSearch = () => {
      currentPage.value = 1
      loadNoticeList()
    }
    
    const deletePublish = async (item) => {
      try {
        await ElMessageBox.confirm('确定要删除这条发布吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await apiDeleteAnnouncement(item.id, {
          publisher: currentUser.value
        })
        
        if (response.code === 200) {
          ElMessage.success('删除成功')
          loadMyAnnouncements()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const viewSignups = (item) => {
      // 跳转到报名管理页面
      router.push({
        name: 'NoticeDetail',
        params: { id: item.id },
        query: { tab: 'signups' }
      })
    }
    
    const openDraftDialog = () => {
      showDraftDialog.value = true
      loadDraftList()
    }
    
    const openMySignupDialog = () => {
      showMySignupDialog.value = true
      loadMySignups()
    }
    
    const openMyPublishDialog = () => {
      showMyPublishDialog.value = true
      loadMyAnnouncements()
    }
    
    // 生命周期
    onMounted(() => {
      loadNoticeList()
      loadMySignups()
    })

    onActivated(() => {
      // 当页面重新激活时（从详情页返回），重新加载列表以更新阅读状态
      loadNoticeList()
    })

    return {
      activeTab,
      currentPage,
      pageSize,
      total,
      noticeList,
      draftList,
      mySignups,
      mySignupList,
      myAnnouncements,
      myPublishList,
      searchKeyword,
      loading,
      loadingMyAnnouncements,
      draftCount,
      imageList,
      attachmentList,
      
      showPublishDialog,
      showSignupDialog,
      showDraftDialog,
      showMySignups,
      showMySignupDialog,
      showMyAnnouncements,
      showMyPublishDialog,
      
      publishForm,
      signupForm,
      publishRules,
      signupRules,
      
      currentUser,
      userRole,
      isAdmin,
      isStaff,
      
      loadNoticeList,
      loadDraftList,
      loadMySignups,
      loadMyAnnouncements,
      openSignupDialog,
      submitSignup,
      publishNotice,
      saveAsDraft,
      handleClosePublishDialog,
      deleteNotice,
      editDraft,
      publishDraft,
      deleteDraft,
      viewDetail,
      getActivityStatusText,
      getActivityStatusType,
      getStatusType,
      getStatusText,
      getButtonText,
      canUserSignup,
      formatTime,
      getTagType,
      getTypeLabel,
      getSignupStatusType,
      getSignupStatusText,
      handleImageChange,
      handleImageRemove,
      handleTabClick,
      handleSizeChange,
      handleCurrentChange,
      handleSearch,
      deletePublish,
      viewSignups,
      openDraftDialog,
      openMySignupDialog,
      openMyPublishDialog,
      handleAttachmentChange,
      handleAttachmentRemove
    }
  }
}
</script>

<style scoped>
.notice-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.left-section {
  flex: 1;
}

.page-title {
  margin: 0 0 15px 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.filter-tabs {
  margin-top: 10px;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-section {
  display: flex;
  align-items: center;
}

.admin-actions,
.user-actions {
  display: flex;
  gap: 10px;
}

.notice-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.notice-item {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
}

.notice-item:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.notice-item.unread {
  border-left: 4px solid #f56c6c;
  background-color: #fef0f0;
}

.notice-item.unread .notice-title {
  font-weight: bold;
}

.notice-header {
  margin-bottom: 15px;
}

.notice-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.title-text {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  flex: 1;
}

.notice-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #909399;
}

.publisher,
.publish-time,
.location {
  display: flex;
  align-items: center;
  gap: 5px;
}

.notice-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.notice-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.admin-item-actions {
  display: flex;
  gap: 5px;
}

.activity-info {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #909399;
}

.limit-info,
.deadline-info {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框样式 */
.dialog-form {
  max-width: 600px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

/* 徽章样式 */
.draft-badge,
.unread-badge {
  margin-left: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .top-bar {
    flex-direction: column;
    gap: 15px;
  }
  
  .right-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-section {
    width: 100%;
  }
  
  .search-section .el-input {
    width: 100%;
  }
  
  .notice-meta {
    flex-direction: column;
    gap: 5px;
  }
  
  .notice-footer {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .activity-info {
    flex-direction: column;
    gap: 5px;
  }
}

/* 未读公告样式 */
.notice-item.unread {
  border-left: 4px solid #f56c6c;
  background-color: #fef0f0;
}

.notice-item.unread .notice-title {
  font-weight: bold;
}

.draft-list,
.my-signup-list,
.my-publish-list {
  max-height: 500px;
  overflow-y: auto;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.draft-item,
.signup-item,
.publish-item {
  margin-bottom: 15px;
}

.draft-header,
.signup-header,
.publish-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.draft-title,
.signup-title,
.publish-title {
  flex: 1;
  font-weight: bold;
  color: #303133;
}

.draft-time,
.signup-time,
.publish-time {
  color: #909399;
  font-size: 12px;
}

.draft-actions,
.publish-actions {
  display: flex;
  gap: 10px;
}

.signup-content p {
  margin: 5px 0;
  color: #606266;
}
</style> 
